﻿package tiji.game{

	import flash.events.Event;
	import flash.display.*;
	import flash.geom.*;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	import flash.events.MouseEvent;
	import flash.system.LoaderContext;
	
	public class PuzzleGame extends Sprite {
		public function PuzzleGame() {
/*			_control = control;
			var playerId:int = _control.player.getPlayerId();
			_control.agent.sendMessage("playerStarted", playerId);*/
			init();
		}
		public function init():void {
			puzzleBoardClip = new MovieClip();
			addChild(puzzleBoardClip);
			totalPuzzlePieces = Math.pow(difficulty, 2);
			//imagesArr = new Array("image1.jpg", "image2.jpg", "image3.jpg");
			puzzlePiecesArr = new Array();
			puzzlePiecesFound = new Array();
			correctPuzzlePieces = 0;
			threshold = 0xFFFF;
			/* Create the image Loader */
			imageLoader = new Loader();
			imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,
			onLoadImg);
			/* Create the URL Request */
			var index:Number = Math.floor(Math.random() * imagesArr.length);
			var puzzleObject:Object = imagesArr[index];
			var urlString:String = puzzleObject["imageUrl"];
			requestURL = new URLRequest(urlString);
			// Make sure we can load from an external site
			var loaderContext:LoaderContext = new LoaderContext();
			loaderContext.checkPolicyFile = true;
			// Load the image
			imageLoader.load(requestURL, loaderContext);
			// Setup a holdery mc to hold the puzzle pieces
			holder = new MovieClip();
			addChild(holder);
		}

		protected function onLoadImg(evt:Event):void {
			// Determine the width and height of each puzzle piece.
			// Each puzzle consists of 4 columns and 2 rows.
			imageLoader.scaleX = .75;
			imageLoader.scaleY = .75;

			var widthPuzzlePiece:Number = imageLoader.width / Math.sqrt(totalPuzzlePieces);
			var heightPuzzlePiece:Number = imageLoader.height / Math.sqrt(totalPuzzlePieces);
			// Draw the image from the movie clip into a BitmapData Obj.
			puzzleBmp = new BitmapData(imageLoader.width, imageLoader.height);
			puzzleBmp.draw(imageLoader, new Matrix());
			var puzzlePieceBmp:BitmapData;
			var x:Number = 0;
			var y:Number = 0;
			// Loop x times to make each piece
			for (var i:Number = 0; i < totalPuzzlePieces; i++) {
				puzzlePieceBmp = new BitmapData(widthPuzzlePiece, heightPuzzlePiece);
				puzzlePieceBmp.copyPixels(puzzleBmp, new Rectangle(x,y,widthPuzzlePiece,heightPuzzlePiece), new Point(0,0));

				makePuzzlePiece(puzzlePieceBmp, i);

				x += widthPuzzlePiece;
				trace("changex" + i);
				if (x >= puzzleBmp.width) {
					x = 0;
					y += heightPuzzlePiece;
					trace("changey" + i);
				}
			}
			makePuzzleBoard(puzzleBmp.width, puzzleBmp.height);
			arrangePuzzlePieces();
		}
		protected function makePuzzlePiece(puzzlePiece:BitmapData, index:int):void {
			var puzzlePieceClip:Bitmap = new Bitmap(puzzlePiece);
			var tmp2:MovieClip = new MovieClip();
			tmp2.addChild(puzzlePieceClip);
			tmp2.name = String(index);// Added for Strict Mode
			holder.addChild(tmp2);
			holder.addEventListener("mouseDown", pieceMove);
			holder.addEventListener("mouseUp", pieceMove);
			puzzlePiecesArr.push(tmp2);
			// This is used to check if the same piece has been placed
			puzzlePiecesFound.push(tmp2.name);
		}
		protected function pieceMove(evt:Event):void {
			if (evt.type == "mouseDown") {
				evt.target.startDrag();
			} else if (evt.type == "mouseUp") {
				evt.target.stopDrag();
				var puzzlePieceIndex:Number = evt.target.name;
				// ADDED VV 4.3. Check if droppped inside of the grid
				if (evt.target.dropTarget) {
					var puzzleBoardSpaceIndex:Number =
					evt.target.dropTarget.name;
				}
				if (puzzlePieceIndex == puzzleBoardSpaceIndex) {
					var coordinate:Point = new
					Point(evt.target.dropTarget.x, evt.target.dropTarget.y);
					var coordinateGlobal:Point = new Point();
					coordinateGlobal =
					puzzleBoardClip.localToGlobal(coordinate);
					if (puzzlePiecesFound.length != 0) {
						for (var i:int = 0; i < puzzlePiecesFound.length; i++) {
							if (puzzlePiecesFound[i] == puzzlePieceIndex) {
								puzzlePiecesFound[i] = "Correct";
								correctPuzzlePieces++;
								if (_checkmc != null) {
									removeChild(_checkmc);
									_checkmc = new checkMC();
									_checkmc.x = (550);
									_checkmc.y = (0);
									addChild(_checkmc);
								} else {
									_checkmc = new checkMC();
									_checkmc.x = (550);
									_checkmc.y = (0);
									addChild(_checkmc);
								}
							}
						}
					}
					if (correctPuzzlePieces == totalPuzzlePieces) {
						holder.visible = false;
						var tmp:Bitmap = new Bitmap(puzzleBmp);
						puzzleBoardClip.addChild(tmp);
						
						
						_arrowmc = new arrowMC();
						_arrowmc.x = (650);
						_arrowmc.y = (0);
						addChild(_arrowmc);
						_arrowmc.addEventListener(MouseEvent.MOUSE_DOWN, puzzleSolved);
					}
				}
			}
		}
		protected function arrangePuzzlePieces():void {
			var widthPuzzlePiece:Number = puzzlePiecesArr[0].width;
			var heightPuzzlePiece:Number = puzzlePiecesArr[0].height;
			var locationArr:Array = new Array();
			var locx:Number = 10;
			var locy:Number = 10;
			while(locationArr.length<totalPuzzlePieces){
				locationArr.push({x:locx, y:locy});
				locy += ((heightPuzzlePiece + 2));
				if(locy >= height)
				{
					locy = 10;
					locx += (widthPuzzlePiece + 2);
				}
			}
			var index:Number = 0;
			var coordinates:Object;
			while (locationArr.length > 0) {
				coordinates = locationArr.splice(Math.floor(Math.random()
				* locationArr.length), 1)[0];
				puzzlePiecesArr[index].x = coordinates.x;
				puzzlePiecesArr[index].y = coordinates.y;
				index++;
			}
		}
		protected function makePuzzleBoard(width:Number, height:Number):void {
			var widthPuzzlePiece:Number = width / Math.sqrt(totalPuzzlePieces);
			var heightPuzzlePiece:Number = height / Math.sqrt(totalPuzzlePieces);
			var puzzleBoardSpaceClip:MovieClip;
			var x:Number = 0;
			var y:Number = 0;
			for (var i:Number = 0; i < totalPuzzlePieces; i++) {
				puzzleBoardSpaceClip = new MovieClip();
				puzzleBoardSpaceClip.graphics.lineStyle(0);
				puzzleBoardSpaceClip.graphics.beginFill(0xFFFFFF, 50);
				puzzleBoardSpaceClip.graphics.lineTo(widthPuzzlePiece,0);
				puzzleBoardSpaceClip.graphics.lineTo(widthPuzzlePiece,heightPuzzlePiece);
				puzzleBoardSpaceClip.graphics.lineTo(0,heightPuzzlePiece);
				puzzleBoardSpaceClip.graphics.lineTo(0,0);
				puzzleBoardSpaceClip.graphics.endFill();
				puzzleBoardSpaceClip.x = x;
				puzzleBoardSpaceClip.y = y;
				x += widthPuzzlePiece;
				if (x >= width) {
					x = 0;
					y += heightPuzzlePiece;
				}
				puzzleBoardSpaceClip.name = String(i);// Added for Strict Mode
				puzzleBoardClip.addChild(puzzleBoardSpaceClip);
			}
			puzzleBoardClip.x = 350;
			puzzleBoardClip.y = 200 - puzzleBoardClip.height/2;
		}
		protected function puzzleSolved(... ignored):void {
			_arrowmc.removeEventListener(MouseEvent.MOUSE_DOWN, puzzleSolved);
			removeChild(_arrowmc);
			var timer:Timer = new Timer(50);
			timer.start();
			timer.addEventListener("timer", puzTrash);
		}
		protected function puzTrash(evt:Event):void {
			if (threshold > 0xFFFFFF) {
				threshold = 0xFFFFFF;
				evt.target.stop();
				init();
			}
			puzzleBmp.threshold(puzzleBmp, new Rectangle(0,0,
			puzzleBmp.width, puzzleBmp.height), new Point(0,0), "<=",
			0xFF000000 | threshold);
			threshold *= 1.2;
		}
		protected var puzzlePiecesArr:Array;
		protected var puzzlePiecesFound:Array;
		protected var topDepth:Number;
		protected var totalPuzzlePieces:Number;
		protected var correctPuzzlePieces:Number;
		protected var puzzleBmp:BitmapData;
		protected var intervalID:Number;
		protected var threshold:Number;
		protected var imageLoader:Loader;
		protected var requestURL:URLRequest;
		protected var puzzleBoardClip:MovieClip;
		protected var holder:MovieClip;
		
		protected var difficulty:int = 7;
		protected var roomPacks:int = 0;
		
		protected var _checkmc :MovieClip;
		protected var _arrowmc :MovieClip;
		
		protected var iOF1:Object = {imageName:"Flower 1", imageUrl:"http://www.helpexamples.com/flash/images/image1.jpg" };
		protected var iOF2:Object = {imageName:"Flower 2", imageUrl:"http://www.helpexamples.com/flash/images/image2.jpg" };
		protected var iOF3:Object = {imageName:"Flower 3", imageUrl:"http://www.helpexamples.com/flash/images/image3.jpg" };
		
		protected var imagesArr:Array = new Array(iOF1, iOF2, iOF3);
		
/*		protected var imageObjectDali:Object = {imageName:"Untitled by Dali", imageUrl:"http://mediacloud.whirled.com/315b7cd542645f31cbafaee4473dab02eb5f6c47.jpg"};
		protected var imageObjectDarkKnight:Object = {imageName:"The Dark Knight", imageUrl:"http://mediacloud.whirled.com/c9e0ee004bd8a4d446bc89a0c282582e219bd978.jpg"};
		protected var imageObjectFlower1:Object = {imageName:"Flower 1", imageUrl:"http://mediacloud.whirled.com/3e1df3e7aff0de841545bafe2a8fba6159ea4955.jpg"};
		protected var imageObjectFlower2:Object = {imageName:"Flower 2", imageUrl:"http://mediacloud.whirled.com/8b7ca5d3396095a9703f7d62a53d8ef29ef70869.jpg"};
		protected var imageObjectFlower3:Object = {imageName:"Flower 3", imageUrl:"http://mediacloud.whirled.com/912866503e86d16bc080fec247f82ecaf69982d4.jpg"};
		protected var imageObjectMonet:Object = {imageName:"Bridge over a Pond of Water Lilies by Monet", imageUrl:"http://mediacloud.whirled.com/8a7a16d5578205571cc8ca5baf6511e97d4c64ea.jpg"};
		protected var imageObjectPicasso:Object = {imageName:"Rest by Picasso", imageUrl:"http://mediacloud.whirled.com/7ced62c0962aff0149d50ec3fea060eeb04c55ec.jpg"};
		protected var imageObjectGogh:Object = {imageName:"Starry Night over the Rhone by Van Gogh", imageUrl:"http://mediacloud.whirled.com/c55fae878fc668523eed04b893a1396f8e98cc78.jpg"};
		protected var imageObjectButterfly:Object = {imageName:"Butterfly", imageUrl:"http://mediacloud.whirled.com/b5174610dd3292267b5dd5a09bf0db8ad01cd1c5.jpg"};
		
		 
		protected var imagesArr:Array = new Array(imageObjectDali, imageObjectDarkKnight, imageObjectFlower1, 
												  imageObjectFlower2, imageObjectFlower3
												  , imageObjectMonet, imageObjectPicasso, imageObjectGogh, 
												  imageObjectButterfly);*/
		
		[Embed(source="F:/whirled/tiji/resources/swfs/checkmc.swf")]
		public var checkMC:Class;
		
		[Embed(source="F:/whirled/tiji/resources/swfs/arrowmc.swf")]
		public var arrowMC:Class;
	}
} 